package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.article.service.ApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

@Service
public class ApArticleFreemarkerServiceImpl implements ApArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleService apArticleService;

    @Async("taskExecutor")
    @Override
    public void generateHtml(ApArticle apArticle, String content) {

        //1.为Freemaker模板准备MAP数据
        Map map = new HashedMap();
        map.put("content", JSONArray.parse(content));

        try {
            //2.生成HTML
            Template template = configuration.getTemplate("article.ftl");
            StringWriter out = new StringWriter();
            template.process(map, out);

            ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes());

            //3.将html写入到MinIO中获取URL
            String url = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", in);

            //4.将URL更新到文章的static_url中
            ApArticle apArticleDB = new ApArticle();
            apArticleDB.setId(apArticle.getId());
            apArticleDB.setStaticUrl(url);
            apArticleService.updateById(apArticleDB);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
